<template>
  <div class="hazardous-chemicals-management bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-6">危险化学品管理</h2>

    <div class="search-form bg-card text-card-foreground shadow-md rounded-lg mb-6 p-6">
      <!-- <div class="flex flex-wrap gap-4 ">
        <div class="flex-1">
          <label for="chemicalName" class="block text-sm font-medium">化学品名称：</label>
          <input id="chemicalName" v-model="filters.chemicalName" type="text" placeholder="请输入" class="input" />
        </div>
        <div class="flex-1">
          <label for="chemicalType" class="block text-sm font-medium">化学品类别：</label>
          <select id="chemicalType" v-model="filters.chemicalType" class="input">
            <option value="">全部</option>
            <option value="产品">产品</option>
            <option value="原料">原料</option>
          </select>
        </div>
        <div style="visibility: hidden;" class="flex-1">
          <label for="chemicalType" class="block text-sm font-medium">化学品类别：</label>

        </div>
        <div style="visibility: hidden;" class="flex-1">
          <label for="chemicalType" class="block text-sm font-medium">化学品类别：</label>

        </div>
        <div class="flex items-end space-x-2">
          <button @click="search" class="btn btn-primary">查询</button>
          <button @click="resetFilters" class="btn btn-secondary">重置</button>
        </div>
      </div> -->
      <query-form :model="filters" :formItems="formItems" @search="loadData" @reset="resetFilters" />
    </div>

    <div class="mb-4 space-x-2">

      <!-- <button @click="addNew" class="btn btn-primary">

          新增
        </button>
        <button @click="deleteSelected" class="btn btn-destructive">

          删除
        </button>
        <label for="importFile" class="btn btn-secondary">

          导入
        </label>
        <input id="importFile" type="file" @change="importData" accept=".xlsx, .xls" class="hidden" />
        <button @click="exportData" class="btn btn-secondary">

          导出
        </button> -->
      <el-button type="primary" @click="addNew" style="width: 75px; height: 30px;">新增</el-button>
      <el-button @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
      <!-- <el-button style="width: 75px; height: 30px;">导入</el-button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>

    </div>

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <!-- <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-border">
          <thead>
            <tr class="bg-muted">
              <th class="table-header w-[60px]">
                <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
              </th>
              <th v-for="header in tableHeaders" :key="header" class="table-header">
                {{ header }}
              </th>
              <th class="table-header">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in paginatedData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.selected" class="checkbox" />
              </td>
              <td class="table-cell">{{ startIndex + index + 1 }}</td>
              <td class="table-cell">{{ item.chemicalName }}</td>
              <td class="table-cell">{{ item.chemicalType }}</td>
              <td class="table-cell">{{ item.quantity }}</td>
              <td class="table-cell">{{ item.manufacturer }}</td>
              <td class="table-cell">{{ item.date }}</td>
              <td class="table-cell">{{ item.type }}</td>
              <td class="table-cell">{{ item.storageArea }}</td>
              <td class="table-cell">
                <a href="#" class="text-blue-600 hover:text-blue-800">
                  <DownloadIcon class="w-4 h-4 inline-block" />
                </a>
              </td>
              <td class="table-cell">
                <button @click="editItem(item)" class="btn btn-sm btn-secondary">编辑</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div> -->
      <el-table v-loading="loading" :data="paginatedData" style="width: 100%" @selection-change="handleSelectionChange"
        ref="tableRef" align="center" class="data-table" :header-cell-style="headerCellStyle" empty-text="暂无数据"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ startIndex + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="CHEMICALS_NAME" label="化学品名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="CHEMICALS_TYPE" label="化学品类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ACCESS_TYPE" label="进出类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="QUANTITY" label="数量" header-align="center" align="center"></el-table-column>
        <el-table-column prop="UNIT" label="单位" header-align="center" align="center"></el-table-column>
        <el-table-column prop="MANUFACTURER_INFO" label="厂家信息" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DATEYEAR" label="日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.DATEYEAR) }}
          </template>
        </el-table-column>
        <el-table-column prop="STORAGE_AREA" label="存储区域" header-align="center" align="center"></el-table-column>
        <el-table-column prop="MSDS_FILE" label="MSDS说明书" header-align="center" align="center">
<template #default="scope">

  <div>{{ scope.row.MSDS_FILE }}</div>

          <el-button v-if="scope.row.MSDS_FILE!=null "  style="width: 75px; height: 30px;"
            @click="uploadfile(apiBaseUrl + '/download/' + scope.row.MSDS_FILE)">
            下载查看
          </el-button>

</template>



        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editItem(scope.row)" link>编辑</el-button>
            <!-- <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
      <!-- <div>
        <p class="text-sm">
          共 <span class="font-medium">{{ totalItems }}</span> 条
        </p>
      </div>
      <div>
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="prevPage" :disabled="currentPage === 1" class="btn-pagination">
            上一页
          </button>
          <button v-for="page in displayedPages" :key="page" @click="goToPage(page)"
            :class="['btn-pagination', currentPage === page ? 'bg-primary text-primary-foreground' : 'bg-card text-card-foreground hover:bg-muted']">
            {{ page }}
          </button>
          <button @click="nextPage" :disabled="currentPage === totalPages" class="btn-pagination">
            下一页
          </button>
        </nav>
      </div> -->
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <!-- <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" @close="closeDialog"
      class="bg-background text-foreground">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="化学品名称" prop="chemicalName">
          <el-input v-model="formData.chemicalName" class="input"></el-input>
        </el-form-item>
        <el-form-item label="化学品类别" prop="chemicalType">
          <el-select v-model="formData.chemicalType" class="input">
            <el-option label="产品" value="产品"></el-option>
            <el-option label="原料" value="原料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量(KG)" prop="quantity">
          <el-input v-model="formData.quantity" type="number" class="input"></el-input>
        </el-form-item>
        <el-form-item label="厂家信息" prop="manufacturer">
          <el-input v-model="formData.manufacturer" class="input"></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-input v-model="formData.date" type="date" class="input"></el-input>
        </el-form-item>
        <el-form-item label="进出类型" prop="type">
          <el-select v-model="formData.type" class="input">
            <el-option label="进园" value="进园"></el-option>
            <el-option label="出园" value="出园"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存储区域" prop="storageArea">
          <el-input v-model="formData.storageArea" class="input"></el-input>
        </el-form-item>
        <el-form-item label="MSDS说明书" prop="msdsDoc">
          <el-upload class="upload-demo" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :on-success="handleUploadSuccess">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" class="btn btn-secondary">取 消</el-button>
          <el-button type="primary" @click="saveChemical" class="btn btn-primary">确 定</el-button>
        </span>
      </template>
    </el-dialog> -->
    <el-dialog class="dialog-from" v-model="dialogVisible" :title="isDialogType == 'add' ? '危险化学品新增' : '危险化学品编辑'"
      width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="formData" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="化学品名称：" label-position="top" prop="CHEMICALS_NAME">
                  <el-input v-model="formData.CHEMICALS_NAME" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="化学品类别：" label-position="top" prop="CHEMICALS_TYPE">
                  <el-select v-model="formData.CHEMICALS_TYPE" placeholder="请选择" clearable>
                    <el-option label="产品" value="产品" />
                    <el-option label="中间产品" value="中间产品" />
                    <el-option label="进口化学品" value="进口化学品" />
                    <el-option label="原料" value="原料" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="数量(KG)：" label-position="top" prop="QUANTITY">
                  <el-input type="number" v-model="formData.QUANTITY" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="单位：" label-position="top" prop="UNIT">
                  <el-select v-model="formData.UNIT" placeholder="请选择" clearable>
                    <el-option label="陕西侨岭润岳生物科技有限公司" value="陕西侨岭润岳生物科技有限公司" />
                    <el-option label="陕西格丽达生物科技有限公司" value="陕西格丽达生物科技有限公司" />
                    <el-option label="陕西妙龙居新材料科技有限公司" value="陕西妙龙居新材料科技有限公司" />
                    <el-option label="大荔瑞联新材料股份有限责任公司" value="大荔瑞联新材料股份有限责任公司" />
                    <el-option label="大荔海泰新材料有限责任公司" value="大荔海泰新材料有限责任公司" />
                    <el-option label="陕西科谱华生物科技有限公司" value="陕西科谱华生物科技有限公司" />
                    <el-option label="陕西北农华绿色生物技术有限公司" value="陕西北农华绿色生物技术有限公司" />
                    <el-option label="陕西萌益生物科技有限公司" value="陕西萌益生物科技有限公司" />
                    <el-option label="西安益维聚泰新材料科技有限公司" value="西安益维聚泰新材料科技有限公司" />
                    <el-option label="西安德立生物化工有限公司" value="西安德立生物化工有限公司" />
                    <el-option label="陕西同州蔚隆化学科技有限公司" value="陕西同州蔚隆化学科技有限公司" />
                    <el-option label="陕西港华生物科技有限公司" value="陕西港华生物科技有限公司" />
                    <el-option label="陕西迈祥有机玻璃科技有限公司" value="陕西迈祥有机玻璃科技有限公司" />
                    <el-option label="陕西英唐食用新材料科技有限公司" value="陕西英唐食用新材料科技有限公司" />
                    <el-option label="光大绿色环保城乡再生能源（大荔）有限公司" value="光大绿色环保城乡再生能源（大荔）有限公司" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="厂家信息：" label-position="top" prop="MANUFACTURER_INFO">
                  <el-input v-model="formData.MANUFACTURER_INFO" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="日期：" label-position="top" prop="DATEYEAR">
                  <input type="datetime-local" id="newPassTime" v-model="formData.DATEYEAR"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="进出类型：" label-position="top" prop="ACCESS_TYPE">
                  <el-select v-model="formData.ACCESS_TYPE" placeholder="请选择" clearable>
                    <el-option label="进" value="进" />
                    <el-option label="出" value="出" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="存储区域：" label-position="top" prop="STORAGE_AREA">
                  <el-input v-model="formData.STORAGE_AREA" placeholder="请输入" />
                </el-form-item>
              </el-col>
                <el-col :span="8">
                  <el-form-item label="MSDS说明书：" label-position="top" prop="MSDS_FILE">
                    <input type="file" id="importFile" @change="handleRISK_HAS" accept=".csv, .xlsx, .pdf" class="mt-1 block w-full">
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确认</el-button>
            <el-button @click="closeAddDialog">
              取消
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()
import {  uploadfile, checkval } from '#/utils/exportfile.js'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus'
const apiBaseUrl = ref(proxy.$currentUrl + '/api/hazardous_management')

const filters = ref({
  CHEMICALS_NAME: '',
  CHEMICALS_TYPE: ''
})

const tableHeaders = ['序号', '化学品名称', '化学品类别', '数量(KG)', '厂家信息', '日期', '进出类型', '存储区域', 'MSDS说明书', '操作']

const chemicalsData = ref([])
const currentPage = ref(1)
const itemsPerPage = 10
const selectAll = ref(false)
const isEditing = ref(false)
const pageSize = ref(10)
const formData = ref({
  ID: null,
  CHEMICALS_NAME: '',
  CHEMICALS_TYPE: '',
  UNIT: '',
  QUANTITY: '',
  MANUFACTURER_INFO: '',
  DATEYEAR: '',
  ACCESS_TYPE: '',
  STORAGE_AREA: '',
  // MSDS_manual: ''
  files: []
})


const handleRISK_HAS = (event) => {
  formData.value.files = []
  const files = Array.from(event.target.files)
  formData.value.files = files[0]
}

const totalItems = computed(() => chemicalsData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)


// const startIndex = computed(() => (currentPage.value - 1) * itemsPerPage)
// const endIndex = computed(() => Math.min(startIndex.value + itemsPerPage, totalItems.value))

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return chemicalsData.value.slice(start, end)
})

const loadData = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: filters.value,
    })
    chemicalsData.value = response.data
    currentPage.value = 1
    loading.value = false
  } catch (error) {
    console.error('获取危化品管理失败:', error)
    alert(
      '获取危化品管理失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const resetFilters = () => {
  filters.value = {
    CHEMICALS_NAME: '',
    CHEMICALS_TYPE: ''
  }
  loadData() // 重新加载所有数据
}

const rules = reactive({
  chemicals_name: [
    { required: true, message: '请输入化学品名称', trigger: 'blur' },
  ],
  chemicals_type: [
    { required: true, message: '请选择化学品类别', trigger: 'change' },
  ],
  quantity: [
    { required: true, message: '请输入数量(KG)', trigger: 'blur' },
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' },
  ],
  manufacturer_infor: [
    { required: true, message: '请输入厂家信息', trigger: 'blur' },
  ],
  dateyear: [
    { required: true, message: '请输入日期', trigger: 'blur' },
  ],
  access_type: [
    { required: true, message: '请选择进出类型', trigger: 'change' },
  ],
  storage_area: [
    { required: true, message: '请输入存储区域', trigger: 'blur' },
  ],
  // MSDS_manual: [
  //   { required: true, message: '请上传MSDS说明书', trigger: 'change' },
  // ],
})

const formRef = ref(null)
const showForm = ref(false)

const dialogVisible = ref(false)
const dialogTitle = computed(() => isEditing.value ? '编辑危化品' : '新增危化品')

const addNew = () => {
  isEditing.value = false
  dialogVisible.value = true
  isDialogType.value = 'add'
  formData.value = {
    ID: null,
    CHEMICALS_NAME: '',
    CHEMICALS_TYPE: '',
    UNIT: '',
    QUANTITY: '',
    MANUFACTURER_INFO: '',
    DATEYEAR: '',
    ACCESS_TYPE: '',
    STORAGE_AREA: '',
    // MSDS_manual: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const editItem = (item) => {
  isEditing.value = true
  dialogVisible.value = true
  isDialogType.value = 'edit'
  formData.value = { ...item }
  formData.value.DATEYEAR = formatDateTimeForInput(item.DATEYEAR)
  console.log('formData.value', formData.value)
}

const viewItem = (item) => {
  isEditing.value = false
  dialogVisible.value = true
  formData.value = { ...item }
}
// 新增提交
const handleSubmit = () => {
  try {
    formRef.value.validate(async (valid) => {
      if (valid) {
        console.log('formData.value', formData.value)
        if (!formData.value.ID) {
          const response = await axios.post(`${apiBaseUrl.value}/add`, formData.value,  {
            headers: {
                  'Content-Type': 'multipart/form-data'
                }
          })
          alert(response.data.message || '创建危险化学品记录成功')
        } else {
          const response = await axios.put(`${apiBaseUrl.value}/update/${formData.value.ID}`, formData.value,{
            headers: {
          'Content-Type': 'multipart/form-data'
        }
          })
          alert(response.data.message || '更新危险化学品记录成功')
        }
        await loadData()
        closeAddDialog()
      }
    })
  } catch (error) {
    console.error('创建危险化学品失败:', error)
    alert(
      '创建危险化学品失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const closeAddDialog = () => {
  dialogVisible.value = false
  resetExpertForm()
}
const resetExpertForm = () => {
  formData.value = {
    ID: null,
    CHEMICALS_NAME: '',
    CHEMICALS_TYPE: '',
    UNIT: '',
    QUANTITY: '',
    MANUFACTURER_INFO: '',
    DATEYEAR: '',
    ACCESS_TYPE: '',
    STORAGE_AREA: '',
    // MSDS_manual: ''
  }
}
const saveChemical = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (isEditing.value) {
          const index = chemicalsData.value.findIndex(item => item.id === formData.value.ID)
          if (index !== -1) {
            chemicalsData.value[index] = { ...formData.value }
          }
        } else {
          chemicalsData.value.push({
            id: chemicalsData.value.length + 1,
            ...formData.value,
            selected: false
          })
        }
        ElMessage.success(isEditing.value ? '编辑成功' : '新增成功')
        closeDialog()
      } else {
        ElMessage.error('请填写完整信息')
        return false
      }
    })
  }
}

const closeDialog = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
const tableRef = ref(null)
const deleteSelected = async () => {
  // chemicalsData.value = chemicalsData.value.filter(item => !item.selected)
  // selectAll.value = false
  try {
    if (selectedIds.value.length === 0) {
      alert('请至少选择一条记录进行删除')
      return
    }
    if (!confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
      return
    }
    const deletePromises = selectedIds.value.map(item =>
      axios.delete(`${apiBaseUrl.value}/delete/${item.ID}`)
    )
    await Promise.all(deletePromises)
    alert('删除成功')
    if (tableRef.value) {
      tableRef.value.clearSelection();
    }
    selectedIds.value = []
    await loadData()
    if (currentPage.value > totalPages.value) {
      currentPage.value = totalPages.value;
    }
    // await nextTick(); // 确保 DOM 更新
  }
  catch (error) {
    console.error('删除失败:', error)
    alert('删除失败: ' + (error.response?.data?.message || error.message))
  }
}

const removeItem = (item) => {
  chemicalsData.value = chemicalsData.value.filter(i => i.id !== item.id)
}

const exportData = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new()

  // 准备要导出的数据
  const exportData = chemicalsData.value.map((expert) => ({
    化学品名称: expert.CHEMICALS_NAME,
    化学品类型: expert.CHEMICALS_TYPE,
    进出类型: expert.ACCESS_TYPE,
    数量: expert.QUANTITY,
    单位: expert.UNIT,
    厂家信息: expert.MANUFACTURER_INFO,
    日期: formatDateTime(expert.DATEYEAR),
    存储区域: expert.STORAGE_AREA,
    // MSDS说明书: expert.MSDS_manual,
  }))

  // 将数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 将工作表添加到工作簿，并设置表名为"应急专家管理"
  XLSX.utils.book_append_sheet(wb, ws, '危化品管理')

  // 生成二进制字符串
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为 Blob
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '危化品管理.xlsx'

  // 模拟点击下载
  link.click()

  // 释放 URL 对象
  URL.revokeObjectURL(link.href)
}

// 添加 s2ab 辅助函数
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}


const importData = (event) => {
  const file = event.target.files[0]
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)
    chemicalsData.value = jsonData.map((item, index) => ({
      id: index + 1,
      ...item,
      selected: false
    }))
  }
  reader.readAsArrayBuffer(file)
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  chemicalsData.value.forEach(item => item.selected = selectAll.value)
}
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // loadData()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // loadData()
  }
}
const goToPage = (page) => {
  currentPage.value = page
}
// 添加格式化日期时间的辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const formItems = ref([
  {
    label: '化学品名称：',
    model: 'CHEMICALS_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '化学品类别：',
    model: 'CHEMICALS_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '请选择', value: '' },
      { label: '产品', value: '产品' },
      { label: '中间产品', value: '中间产品' },
      { label: '进口化学品', value: '进口化学品' },
      { label: '原料', value: '原料' },
    ],
  },
]);
const rowKey = (row) => row.id; // 设置行的唯一标识
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const isDialogType = ref('')
const loading = ref(false)
const selectedIds = ref([])
const handleSelectionChange = (selected) => {
  selectedIds.value = selected;
};
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// Initial data load
onMounted(() => {
  loadData()
})

// 添加这些样式相关的计算属性
const btnClasses = computed(() => {
  return 'px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out'
})

const btnPrimaryClasses = computed(() => {
  return [btnClasses.value, 'bg-primary text-primary-foreground hover:bg-primary/90']
})

const btnSecondaryClasses = computed(() => {
  return [btnClasses.value, 'bg-secondary text-secondary-foreground hover:bg-secondary/80']
})

const btnDestructiveClasses = computed(() => {
  return [btnClasses.value, 'bg-destructive text-destructive-foreground hover:bg-destructive/90']
})

// 更新你的模板以使用这些计算属性作为按钮类
</script>

<style scoped>
/* .input {
  @apply mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.table-header {
  @apply px-6 py-3 text-left text-xs font-medium uppercase tracking-wider;
}

.table-cell {
  @apply px-6 py-4 whitespace-nowrap text-sm;
}

.btn-pagination {
  @apply relative inline-flex items-center px-4 py-2 border border-border text-sm font-medium;
}

/* 覆盖 Element Plus 的一些样式以匹配我们的主题 */
/* :deep(.el-dialog) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__header) {
  @apply bg-muted text-foreground;
}

:deep(.el-dialog__body) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__footer) {
  @apply bg-muted text-foreground;
} */
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
